var express = require('express');
var router = express.Router();
var Post = require('../models/post.js');
var mongodb = require('../models/db.js');

//服务器一开启，就长期开启数据库，而不是每次连接完毕就关闭数据库，
//否则会导致重复开启数据库的错误。
mongodb.open(function(err,mongodb){
  if(err){
    mongodb.close();
    return ;
  }
});
//摘自网络，截取ip地址
function getClientIp(req) {
    var ipAddress;
    var forwardedIpsStr = req.header('x-forwarded-for');
    if (forwardedIpsStr) {
        var forwardedIps = forwardedIpsStr.split(',');
        ipAddress = forwardedIps[0];
    }
    if (!ipAddress) {
        ipAddress = req.connection.remoteAddress;
    }
    return ipAddress;
}

module.exports = function(app){

  app.get('/',function(req, res){
    console.log('int index.js: GET :');
    Post.get(mongodb, null, function(err, posts){
      if(err) {
        post = [];
        console.log('根本没有posts呀');
      }
      res.render('index',{
        ip : getClientIp(req),
        posts: posts
       });
    });
  });

  app.post('/', function(req, res){
    console.log('int index.js: POST :');
    var post = req.body.post;
    var name = req.body.name;
    var post = new Post(name, post);
    res.redirect('/');
    // post.save(function(err){
    //   if(err){
    //     console.log('in index.js: 保存post出错' + err);
    //   }else{
    //     console.log('in index.js: 保存post成功');
    //   }
    // }, mongodb);


  });
};
